//
//  CTouchAction.cpp
//  Monster_Martial_Arts_Version_0
//
//  Created by chiawei.tseng on 13/1/10.
//
//

#include "CTouchAction.h"
#include "CInputSystem.h"
#include "CMemberCallback.h"
#include "cocos2d.h"

using namespace cocos2d;
using namespace MMA;

CTouchAction::CTouchAction()
{
    m_Data = new TOUCH_DATA();
    
    m_Data->m_inputID = TOUCH_INPUT_ID;
    
    CMemberCallback<CTouchAction>* memberCallBack = new CMemberCallback<CTouchAction>(this,&CTouchAction::HandlResult);
    
    m_Data->m_pCallBackPtr = static_cast<CCallBack*>(memberCallBack);
    
    ((TOUCH_DATA*)m_Data)->m_TouchType = TOUCH_DATA::INVALID_TOUCH_TYPE;
    
    ((TOUCH_DATA*)m_Data)->Team1Member = NULL;
    
    ((TOUCH_DATA*)m_Data)->Team2Member = NULL;
    
    ((TOUCH_DATA*)m_Data)->targetMember = NULL;
}

CTouchAction::~CTouchAction()
{
    delete m_Data;
    
    m_Data = NULL;
}

void CTouchAction::UpdateTouchData(fPoint fpoint,TOUCH_DATA::TOUCH_TYPE touchType)
{
    m_bTriggered = true;
    
    ((TOUCH_DATA*)m_Data)->m_fTouchPoint = fpoint;
    
    ((TOUCH_DATA*)m_Data)->m_TouchType = touchType;
    
    ((TOUCH_DATA*)m_Data)->Team1Member = GetTouchTeamMember(BATTLE_TEAM_RED,fpoint);
    
    ((TOUCH_DATA*)m_Data)->Team2Member = GetTouchTeamMember(BATTLE_TEAM_BLUE,fpoint);
    
    ((TOUCH_DATA*)m_Data)->targetMember = NULL;
    
    if (((TOUCH_DATA*)m_Data)->Team1Member && ((TOUCH_DATA*)m_Data)->Team2Member == NULL)
    {
        ((TOUCH_DATA*)m_Data)->targetMember = ((TOUCH_DATA*)m_Data)->Team1Member;
    }
    else if(((TOUCH_DATA*)m_Data)->Team1Member == NULL && ((TOUCH_DATA*)m_Data)->Team2Member)
    {
        ((TOUCH_DATA*)m_Data)->targetMember = ((TOUCH_DATA*)m_Data)->Team2Member;
    }
    else if(((TOUCH_DATA*)m_Data)->Team1Member && ((TOUCH_DATA*)m_Data)->Team2Member)
    {
        if(((TOUCH_DATA*)m_Data)->Team1Member->GetPoint().Y > ((TOUCH_DATA*)m_Data)->Team2Member->GetPoint().Y)
        {
            ((TOUCH_DATA*)m_Data)->targetMember = ((TOUCH_DATA*)m_Data)->Team1Member;
        }
        else
        {
            ((TOUCH_DATA*)m_Data)->targetMember = ((TOUCH_DATA*)m_Data)->Team2Member;
        }
    }
    
}

CBattleObject* CTouchAction::GetTouchTeamMember(BATTLE_TEAM_NUMBER number,const fPoint& point)
{
    TEAM team = CBattleManager::Get().GetTeam(number);
    
    TeamMemberIter pi = team.m_TeamMember.begin();
    
    CBattleObject* obj = NULL;
    
    while (pi != team.m_TeamMember.end())
    {
        if((*pi)->isAABB(point))
        {
            if (obj == NULL)
            {
                obj = (*pi);
            }
            else
            {
                if (obj->GetPoint().Y < (*pi)->GetPoint().Y)
                {
                    obj = *pi;
                }
            }
        }
        
        pi++;
    }
    
    return obj;
}

void CTouchAction::HandlResult(void* data)
{
    CCLog("into CTouchAction HandlResult");
}
